package com.jrx.anytxn.param.job.investor.file.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.config.InvestorFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrInvestorTable;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrInvestorTableMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author liuyu
 * @Description 联合贷文件合并监听，重跑时删除已有的合并文件和.ok文件
 */
@Service
public class MergeInvestorFileListener implements JobExecutionListener {
	@Autowired
	private IOrganizationTableService organizationTableService;
	@Autowired
	private InvestorFileConfig investorFileConfig;
	@Resource
	private ExtPrInvestorTableMapper extPrInvestorTableMapper;

	@Override
	public void beforeJob(JobExecution jobExecution) {
		String filePath = investorFileConfig.getInvestorFilePath();
		PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
		Date businessDate = org.getToday();
		String toDay = DateUtils.format(businessDate, "yyyyMMdd");
		List<PrInvestorTable> investorList = extPrInvestorTableMapper.selectAllByTableStatus(Constant.STATUS_1);
		if (CollectionUtils.isEmpty(investorList)) {
			return;
		}
		for (PrInvestorTable investorTable : investorList) {
			String investorId = investorTable.getInvestorId();
			String investorPath = filePath + File.separator + org.getTenantId() + File.separator + investorId + File.separator + toDay;
			Path path = Paths.get(investorPath);
			File toFile = path.toFile();

			// 删除合并文件和.ok文件
			if (Files.exists(path) && Files.isDirectory(path)) {
				File[] files = toFile.listFiles();
				if (files.length > 0) {
					for (File file : files) {
						String name = file.getName();
						if (name.endsWith("_" + toDay + ".txt") || name.endsWith(".ok")) {
							file.delete();
						}
					}
				}

			}
		}
	}

	@Override
	public void afterJob(JobExecution jobExecution) {

	}
}
